package br.com.fogas.utils;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

import android.util.Base64;

public class FileUtility extends FileUtils {

	/**
     * Encode image to string
     * @param image The image to encode
     * @param type jpeg, bmp, ...
     * @return encoded string
     */
    public String base64EncodeToString(File file) {
        String imageString = null;
        try {
        	byte[] imageBytes = FileUtils.readFileToByteArray(file);
            imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imageString;
    }
	
    /**
     * Encode image to string
     * @param image The image to encode
     * @param type jpeg, bmp, ...
     * @return encoded string
     */
    public String base64EncodeToStringXmlTag(File file) {
        String imageString = "data:image/jpg;base64,"+base64EncodeToString(file);
        return imageString;
    }
    
	/**
     * Decode string to image
     * @param imageString The string to decode
     * @return decoded image
     */
    public File base64DecodeToFile(File file, String imageString) {
        try {
        	byte[] imageBytes = Base64.decode(imageString, Base64.DEFAULT);
            FileUtils.writeByteArrayToFile(file, imageBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }
}
